import { checkLoginStatus, showMessage } from './common.js';

// 加载用户信息
async function loadUserInfo() {
    const user = await checkLoginStatus();
    if (!user) {
        showMessage('warning', '请先登录');
        window.location.href = 'login.html';
        return;
    }

    try {
        document.getElementById('username-display').textContent = user.username;
        document.getElementById('nickname').value = user.nickname || '';
        document.getElementById('email').value = user.email || '';
        document.getElementById('phone').value = user.phone || '';
        document.getElementById('address').value = user.address || '';

        if (user.avatar) {
            document.getElementById('user-avatar').src = `/uploads/avatars/${user.avatar}`;
        }
    } catch (error) {
        showMessage('error', '加载用户信息失败');
    }
}

// 初始化菜单切换
function initMenu() {
    const menuItems = document.querySelectorAll('.user-menu li');
    const contentSections = document.querySelectorAll('.content-section');

    menuItems.forEach(item => {
        item.addEventListener('click', function(e) {
            e.preventDefault();

            // 更新活动菜单项
            menuItems.forEach(i => i.classList.remove('active'));
            this.classList.add('active');

            // 显示对应内容区
            const targetId = this.querySelector('a').getAttribute('href').substring(1);
            contentSections.forEach(section => {
                section.classList.remove('active');
                if (section.id === targetId) {
                    section.classList.add('active');
                }
            });
        });
    });
}

// 初始化基本信息表单
function initBasicInfoForm() {
    const form = document.getElementById('basic-info-form');
    if (!form) return;

    form.addEventListener('submit', async function(e) {
        e.preventDefault();

        const userData = {
            nickname: document.getElementById('nickname').value,
            email: document.getElementById('email').value,
            phone: document.getElementById('phone').value,
            address: document.getElementById('address').value
        };

        try {
            const response = await auth.updateUser(userData);
            if (response.success) {
                showMessage('success', '信息更新成功');
            } else {
                showMessage('error', response.message || '信息更新失败');
            }
        } catch (error) {
            showMessage('error', '信息更新失败');
        }
    });

    // 取消按钮
    document.getElementById('cancel-edit-basic')?.addEventListener('click', () => {
        loadUserInfo();
    });
}

// 初始化修改密码功能
function initPasswordChange() {
    const changeBtn = document.getElementById('change-password-btn');
    const cancelBtn = document.getElementById('cancel-password-change');
    const form = document.getElementById('change-password-form');

    if (!changeBtn || !form) return;

    changeBtn.addEventListener('click', () => {
        form.classList.remove('hidden');
    });

    cancelBtn.addEventListener('click', () => {
        form.classList.add('hidden');
    });

    form.addEventListener('submit', async function(e) {
        e.preventDefault();

        const currentPassword = document.getElementById('current-password').value;
        const newPassword = document.getElementById('new-password').value;
        const confirmPassword = document.getElementById('confirm-password').value;

        if (newPassword !== confirmPassword) {
            showMessage('error', '两次输入的新密码不一致');
            return;
        }

        try {
            const response = await auth.updateUser({
                currentPassword,
                newPassword
            });

            if (response.success) {
                showMessage('success', '密码修改成功');
                form.reset();
                form.classList.add('hidden');
            } else {
                showMessage('error', response.message || '密码修改失败');
            }
        } catch (error) {
            showMessage('error', '密码修改失败');
        }
    });
}

// 初始化头像上传
function initAvatarUpload() {
    const changeBtn = document.getElementById('change-avatar-btn');
    const modal = document.getElementById('avatar-modal');
    const closeModal = document.querySelector('.close-modal');
    const avatarInput = document.getElementById('avatar-input');
    const uploadBtn = document.getElementById('upload-avatar-btn');

    if (!changeBtn || !modal) return;

    // 打开模态框
    changeBtn.addEventListener('click', () => {
        modal.classList.remove('hidden');
    });

    // 关闭模态框
    closeModal.addEventListener('click', () => {
        modal.classList.add('hidden');
    });

    // 预览选择的图片
    avatarInput.addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(event) {
                document.getElementById('avatar-preview').src = event.target.result;
            };
            reader.readAsDataURL(file);
        }
    });

    // 上传头像
    uploadBtn.addEventListener('click', async function() {
        const file = avatarInput.files[0];
        if (!file) {
            showMessage('warning', '请选择图片');
            return;
        }

        const formData = new FormData();
        formData.append('avatar', file);

        try {
            const response = await upload.image(formData);
            if (response.success) {
                // 更新用户头像
                const userResponse = await auth.updateUser({
                    avatar: response.data.filenames[0]
                });

                if (userResponse.success) {
                    showMessage('success', '头像更新成功');
                    document.getElementById('user-avatar').src = `/uploads/avatars/${response.data.filenames[0]}`;
                    modal.classList.add('hidden');
                }
            }
        } catch (error) {
            showMessage('error', '头像上传失败');
        }
    });
}

// 页面加载时执行
document.addEventListener('DOMContentLoaded', () => {
    loadUserInfo();
    initMenu();
    initBasicInfoForm();
    initPasswordChange();
    initAvatarUpload();
});